package com.anjiplus.template.gaea.business.modules.quartz.service.impl;

import com.anjiplus.template.gaea.business.modules.quartz.mode.TimingModel;
import com.anjiplus.template.gaea.business.modules.quartz.service.QuartzTaskService;
import com.anjiplus.template.gaea.business.modules.quartz.trigger.TriggerManager;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

@Service
public class QuartzTaskImpl implements QuartzTaskService {

    @Autowired
    @Qualifier("schedulerFactoryBeanQuartz")
    private Scheduler scheduler;
    @Autowired
    private TriggerManager triggerManager;

    /**
     * 添加定时任务
     *
     * @param timingModel
     * @throws NoSuchMethodException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     * @throws InstantiationException
     * @throws SchedulerException
     */
    @Override
    public void addTask(TimingModel timingModel) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, SchedulerException {

        // 加入排除日期
//        AnnualCalendar annualCalendar = new AnnualCalendar();
//        GregorianCalendar gregorianCalendar = new GregorianCalendar(2022, 8, 29);
//        annualCalendar.setDayExcluded(gregorianCalendar, true);
//        scheduler.addCalendar("annualCalendar", annualCalendar, false, false);

        // 构建任务信息
        JobDetail jobDetail = JobBuilder.newJob(timingModel.getTaskClass().getDeclaredConstructor().newInstance().getClass())
                .withDescription(timingModel.getDescription())
                .withIdentity(timingModel.getTaskName(), timingModel.getGroupName())
                .build();
        // 构建触发器
        Trigger trigger = triggerManager.build(timingModel);
        // 将任务参数放入触发器中
        if (timingModel.getParam() != null && !timingModel.getParam().isEmpty()) {
            trigger.getJobDataMap().putAll(timingModel.getParam());
        }
        // 启动任务
        scheduler.scheduleJob(jobDetail, trigger);
    }

    /**
     * 修改定时任务
     *
     * @param timingModel
     * @throws SchedulerException
     */
    @Override
    public void updateTask(TimingModel timingModel) throws SchedulerException {
        // 获取到任务
        TriggerKey triggerKey = TriggerKey.triggerKey(timingModel.getTaskName(), timingModel.getGroupName());

        // 构建触发器
        Trigger trigger = triggerManager.build(timingModel);
        // 将任务参数放入触发器中
        if (timingModel.getParam() != null && !timingModel.getParam().isEmpty()) {
            trigger.getJobDataMap().putAll(timingModel.getParam());
        }
        // 将新的触发器绑定到任务标示上重新执行
        scheduler.rescheduleJob(triggerKey, trigger);
    }

    /**
     * 暂停定时任务
     *
     * @param taskName
     * @param groupName
     * @throws SchedulerException
     */
    @Override
    public void pauseTask(String taskName, String groupName) throws SchedulerException {
        scheduler.pauseJob(JobKey.jobKey(taskName, groupName));
    }

    /**
     * 恢复定时任务
     *
     * @param taskName
     * @param groupName
     * @throws SchedulerException
     */
    @Override
    public void resumeTask(String taskName, String groupName) throws SchedulerException {
        scheduler.resumeJob(JobKey.jobKey(taskName, groupName));
    }

    /**
     * 删除定时任务
     *
     * @param taskName
     * @param groupName
     * @throws SchedulerException
     */
    @Override
    public void deleteTask(String taskName, String groupName) throws SchedulerException {
        // 暂停任务对应的触发器
        scheduler.pauseTrigger(TriggerKey.triggerKey(taskName, groupName));
        // 删除任务对应的触发器
        scheduler.unscheduleJob(TriggerKey.triggerKey(taskName, groupName));
        // 删除任务
        scheduler.deleteJob(JobKey.jobKey(taskName, groupName));
    }

    /**
     * 启动所有任务
     */
    @Override
    public void startAllTasks() {
        try {
            scheduler.start();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 关闭定时任务
     */
    @Override
    public void shutdownAllTasks() {
        try {
            if (!scheduler.isShutdown()) {
                scheduler.shutdown();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 添加日志
     * @param
     * @throws
     */
    @Override
    public int loginfo(String methodName, String ts, String state, String inJson, String outJson, String dateid, String yyid,String gsUrl,String TS) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        String logInsert = "INSERT INTO gs_yy_log(methodName, ts, state, inJson, outJson, dateid, yyid, gsUrl ,yyts) " +
                "VALUES " +
                "('"+methodName+"', '"+ts+"', '"+state+"', '"+inJson+"', '"+outJson+"', '"+dateid+"','"+yyid+"','"+gsUrl+"','"+TS+"');";
        int loginsert = jdbcTemplate.update(logInsert);
        return loginsert;
    }

    @Override
    public int insertOrg(String orgName, String orgCode) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        int orgInsert=0;
        //判断中间库是否已经存在，如已存在，不同步
        String selectSQL = "select count(1) as sum from yy_org_orgs where yyCode = '"+orgCode+"'";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(selectSQL);
        if(maps.size()>0){
            orgInsert = 0;
        }else{
            String orgSql = "INSERT INTO yy_org_orgs(name, yyCode) VALUES ("+orgName+","+orgCode+");\n";
            orgInsert = jdbcTemplate.update(orgSql);
        }
        return orgInsert;
    }

    @Override
    public String selectGsCode(String orgCode) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        String gsCode = "";
        //判断中间库是否已经存在，如已存在，不同步
        String selectSQL = "select gsCode from yy_org_orgs where yyCode = '"+orgCode+"'";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(selectSQL);
        if(maps.size()>0){
            gsCode = (String) maps.get(0).get("gsCode");
        }else{

        }
        return gsCode;
    }
}
